package leetcode.f1t100;

import leetcode.struct.ListNode;

/**
 * 反转指定范围的链表
 * https://leetcode.com/problems/reverse-linked-list-ii/
 *
 * @author lichx
 * @createTime 2024/2/5 16:01
 */
public class Q92_ReverseLinkedListII {

    public static void main(String[] args) {
        Q92_ReverseLinkedListII bean = new Q92_ReverseLinkedListII();
        ListNode listNode = bean.reverseBetween(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4,
                new ListNode(5))))), 2, 4);
        while (listNode!= null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode(),start, cur, next;
        newHead.next = head;
        start = newHead;
        for (int i = 0; i < left -1; i++) {
            start = start.next;
        }
        cur = start.next;
        next = cur.next;
        for (int i = 0; i < right - left; i++) {
            cur.next = next.next;
            next.next = start.next;
            start.next = next;
            next = cur.next;
        }
        return newHead.next;
    }
}
